package com.souku.finance.application.http.volley;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;

import com.android.volley.manager.RequestManager;
import com.souku.finance.application.ui.login.LoginActivity;
import com.souku.finance.application.base.ActivityManage;
import com.souku.finance.application.utils.JsonUtil;
import com.souku.finance.application.utils.ShareUtil;
import com.souku.finance.application.utils.ToastUtil;

import java.util.Map;

/**
 * Created by lenovo on 2016/6/6.
 */
public class ReqListener implements RequestManager.RequestListener {

    private Activity activity;
    private RequestSuccessError onrequestOnsuccessOnerror;
    private SuccessError onsuccessOnerror;
    private Success onsuccess;

    public ReqListener(Activity context, RequestSuccessError on) {
        activity = context;
        onrequestOnsuccessOnerror = on;
    }

    public ReqListener(Activity context, SuccessError on) {
        activity = context;
        onsuccessOnerror = on;
    }

    public ReqListener(Activity context, Success on) {
        activity = context;
        onsuccess = on;
    }


    @Override
    public void onRequest() {
        if (onrequestOnsuccessOnerror != null) {
            onrequestOnsuccessOnerror.onRequest();
        }
    }

    @Override
    public void onSuccess(String response, Map<String, String> headers, String url, int actionId) {
        Log.e("data", response);

        if (JsonUtil.getCode(response) == 1002
                || JsonUtil.getMessage(response).equals("缺少用户标识参数")
                || JsonUtil.getMessage(response).equals("token过期，重新登录")) {
            Intent intent = new Intent(activity, LoginActivity.class);
            activity.startActivity(intent);
            ActivityManage.finishOthers(LoginActivity.class);
            new LogoutHelper(activity).getOut();
            ShareUtil.getInstance().getOut();
            ToastUtil.show("登录状态已过期");
            return;
        }
        //继续
        if (onrequestOnsuccessOnerror != null) {
            onrequestOnsuccessOnerror.onSuccess(response);
        } else if (onsuccessOnerror != null) {
            onsuccessOnerror.onSuccess(response);
        } else {
            onsuccess.onSuccess(response);
        }
    }

    @Override
    public void onError(String errorMsg, String url, int actionId) {
        if (onrequestOnsuccessOnerror != null) {
            onrequestOnsuccessOnerror.onError(errorMsg);
        } else if (onsuccessOnerror != null) {
            onsuccessOnerror.onError(errorMsg);
        } else {
            Log.e("ReqListener", errorMsg);
            ToastUtil.show("网络连接错误");
        }
    }
}
